package com.decent.ejfadmin.interceptor;

import com.decent.ejfadmin.annotation.NoEntryLog;
import com.decent.ejfadmin.common.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * 请求日志拦截器配置
 *
 * @author weicx
 * @date 2018/08/22
 */
@Slf4j
@Component
public class WebLogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        StringBuffer uriLog = new StringBuffer();
        // 判断是否需要记录日志
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getMethod().getAnnotation(NoEntryLog.class) != null) {
                return true;
            }
        }
        for (String uri : Constants.NO_LOG_URIS) {
            if (StringUtils.contains(requestURI, uri)) {
                return true;
            }
        }
        Enumeration<String> parameterNames = request.getParameterNames();
        uriLog.append("session:[").append(request.getSession().getAttribute("currentUser")).append("]");
        while (parameterNames.hasMoreElements()) {
            String param = parameterNames.nextElement();
            uriLog.append(param).append("=");
            uriLog.append(Arrays.toString(request.getParameterValues(param)));

        }
        log.info("豆乐卡管理平台请求地址[{}]请求参数[{}]", requestURI, uriLog);
        return true;
    }

}
